<script setup lang="ts">
import {nextTick, onMounted, reactive, ref, watch} from "vue";
import {ElMessage} from "element-plus";
import type {FormInstance} from 'element-plus'
import {QuoteForm, QuoteItemDto} from '@/api/quote/type'
import {addApi, editApi, getDetailByIdApi,getQuoteNumberApi} from '@/api/quote'
import {Plus} from '@element-plus/icons-vue'
import BomDialog from '@/views/compute/bom/bomDialog/index.vue'
import QuoteStructureDialog from "@/views/compute/quote/components/QuoteStructureDialog.vue";

// 定义组件属性
const props = defineProps<{
  quoteId?: number
  mode: string
}>()

// 定义组件事件
const emit = defineEmits(['save-success', 'cancel'])

// 表单ref
const formRef = ref<FormInstance>()

// BOM选择弹框组件实例
const bomDialogRef = ref()

// 初始化表单数据
const formData = reactive<QuoteForm>({
  id: undefined,
  quoteNumber: undefined,
  title: undefined,
  validUntil: undefined,
  status: 'DRAFT',
  totalAmount: 0,
  remarks: undefined,
  quoteItemDtoList: [] as QuoteItemDto[]
})

// 已选BOM
const selectedBoms = ref<any[]>([])

// 表单校验规则
const rules = {
  quoteNumber: [{required: true, message: '请输入报价单号', trigger: 'blur'}],
  title: [{required: true, message: '请输入报价标题', trigger: 'blur'}],
  validUntil: [{required: true, message: '请选择有效期', trigger: 'change'}]
}

// 打开BOM选择弹窗
const openBomSelect = () => {
  bomDialogRef.value.onShow()
}

// BOM多选变化事件处理
const handleBomSelectionChange = (selection: any[]) => {
  selectedBoms.value = selection
}

// 确认BOM选择
const confirmBomSelect = () => {
  selectedBoms.value.forEach((bom) => {
    const exists = formData.quoteItemDtoList.some(
        (item) => item.productCode === bom.bomCode
    )
    if (!exists) {
      formData.quoteItemDtoList.push({
        id: undefined,
        quoteId: formData.id,
        productCode: bom.bomCode,
        productName: bom.bomName,
        productDescription: bom.description,
        quantity: 1,
        unitPrice: bom.totalPrices,
        totalPrice: bom.totalPrices
      })
    }
  })
  calculateTotalAmount()
  bomDialogRef.value.onClose()
}

// 从清单中移除BOM
const removeBom = (index: number) => {
  formData.quoteItemDtoList.splice(index, 1)
  calculateTotalAmount()
}

// 计算单个项目的总价
const calculateItemTotal = (row: QuoteItemDto) => {
  if (row.quantity && row.unitPrice) {
    row.totalPrice = Number((row.quantity * row.unitPrice).toFixed(2))
    calculateTotalAmount()
  }
}

// 计算报价单总金额
const calculateTotalAmount = () => {
  formData.totalAmount = formData.quoteItemDtoList.reduce((total, item) => {
    return total + (Number(item.totalPrice) || 0)
  }, 0)
}

// 处理提交数据
const handleSubmitData = () => {
  const submitData = JSON.parse(JSON.stringify(formData))
  submitData.quoteItemDtoList = submitData.quoteItemDtoList.map(
      (item: QuoteItemDto) => ({
        id: item.id,
        quoteId: submitData.id,
        productCode: item.productCode,
        productName: item.productName,
        productDescription: item.productDescription,
        quantity: Number(item.quantity),
        unitPrice: Number(item.unitPrice),
        totalPrice: Number(item.totalPrice)
      })
  )
  return submitData
}

// 提交表单
const submitForm = async () => {
  if (props.mode === 'view') return

  try {
    await formRef.value?.validate()
    if (formData.quoteItemDtoList.length === 0) {
      ElMessage.warning('请选择BOM')
      return
    }

    const submitData = handleSubmitData()
    if (props.mode === 'add') {
      await addApi(submitData)
    }
    if (props.mode === 'edit') {
      await editApi(submitData)
    }

    ElMessage.success('保存成功')
    emit('save-success')
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('保存失败')
  }
}

// 取消操作
const cancel = () => {
  emit('cancel')
}

// 监听quoteId变化,加载报价单详情
watch(
    () => props.quoteId,
    async (newVal) => {
      if (newVal) {
        try {
          const res = await getDetailByIdApi(newVal)
          if (res?.data) {
            Object.assign(formData, res.data)
            formData.quoteItemDtoList =  res.data.quoteItemVoList
          }
        } catch (error) {
          console.error('获取报价单详情失败:', error)
          ElMessage.error('获取报价单详情失败')
        }
      } else {
        // 新增时重置表单
        Object.assign(formData, {
          id: undefined,
          quoteNumber: undefined,
          title: undefined,
          validUntil: undefined,
          status: 'DRAFT',
          totalAmount: 0,
          remarks: undefined,
          quoteItemDtoList: []
        })
      }
    },
    {immediate: true}
)


// BOM结构弹窗引用
const structureDialogRef = ref()

// 查看结构
const handleViewStructure = (row: QuoteItemDto) => {
  structureDialogRef.value.show(formData.id,row.productCode)
}

// 修改结构中的价格
const confirmQuoteProductUpdate = (row: any) => {
  console.log("更新行", row);

    const existingItem = formData.quoteItemDtoList.find(
        (item) => item.productCode === row.bomCode
    );

    // 如果找到对应的项，更新该项的数据
    if (existingItem) {
      existingItem.quantity = row.quantity;
      existingItem.unitPrice = row.purchasePrice;
      existingItem.totalPrice = row.totalPrices;
    }

  // 重新计算总金额
  calculateTotalAmount();
  // 关闭弹框
  structureDialogRef.value.onClose();
}


// 是否生成报价单单号
const quoteNumber = ref(false)

// 调用接口获取报价单号
const getQuoteNumber =async (val: boolean | string | number) =>{
  if(val) {
    const res =  await getQuoteNumberApi();
    formData.quoteNumber = res.data
  } else {
    formData.quoteNumber = undefined
  }
}
</script>

<template>
  <div class="quote-form">
    <div class="form-header">
      <h3>{{ mode === 'add' ? '新增报价单' : mode === 'edit' ? '编辑报价单' : '报价单详情' }}</h3>
      <div class="form-actions">
        <el-button @click="cancel">取消</el-button>
        <el-button
            type="primary"
            @click="submitForm"
            v-if="mode !== 'view'"
        >
          保存
        </el-button>
      </div>
    </div>

    <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="90px"

    >
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="报价单号" prop="quoteNumber">
            <el-input :disabled="mode === 'view'" v-model="formData.quoteNumber" placeholder="请输入报价单号"/>
          </el-form-item>
        </el-col>

        <el-col span="2">
          <el-switch :disabled="mode === 'view'" v-model="quoteNumber" @change="getQuoteNumber"/>
        </el-col>
        <el-col :span="8">
          <el-form-item label="报价标题" prop="title">
            <el-input :disabled="mode === 'view'" v-model="formData.title" placeholder="请输入报价标题"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="有效期至" prop="validUntil">
            <el-date-picker :disabled="mode === 'view'"
                v-model="formData.validUntil"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="总金额">
            <el-input v-model="formData.totalAmount" disabled>
              <template #append>元</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="状态">
            <el-select v-model="formData.status" style="width: 100%" :disabled="mode === 'view'">
              <el-option label="草稿" value="DRAFT"/>
              <el-option label="已提交" value="SUBMITTED"/>
              <el-option label="已确认" value="CONFIRMED"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注">
        <el-input
            :disabled="mode === 'view'"
            v-model="formData.remarks"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
        />
      </el-form-item>

      <!-- BOM清单 -->
      <el-form-item label="BOM清单">
        <el-button :disabled="mode === 'view'"
            type="primary"
            @click="openBomSelect"
            style="margin-bottom: 10px"
            :icon="Plus"
        >
          添加BOM
        </el-button>
        <el-table :data="formData.quoteItemDtoList" height="290px"  border style="width: 100%">
          <el-table-column type="index" label="序号" width="70"/>
          <el-table-column prop="productCode" label="BOM编码" min-width="120"/>
          <el-table-column prop="productName" label="BOM名称" min-width="120"/>
          <el-table-column prop="quantity" label="数量" width="120">
            <template #default="scope">
              <el-input-number
                  :disabled="mode === 'view'"
                  v-model="scope.row.quantity"
                  :min="1"
                  :precision="0"
                  style="width: 100px"
                  @change="calculateItemTotal(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="unitPrice" label="单价" min-width="120"/>
          <el-table-column prop="totalPrice" label="总价" min-width="120"/>
          <el-table-column prop="productDescription" label="描述" min-width="200" show-overflow-tooltip/>
          <el-table-column label="操作" width="150">

            <template #default="scope">
              <el-button type="primary" size="small"  link @click="handleViewStructure(scope.row)" icon="View">结构</el-button>
              <el-button type="danger" size="small" :disabled="mode === 'view'"   link @click="removeBom(scope.$index)" icon="Delete">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>


    <!-- BOM选择弹框 -->
    <bom-dialog
        ref="bomDialogRef"
        @handleBomSelectionChange="handleBomSelectionChange"
        @confirmBomSelect="confirmBomSelect"
    />


    <!-- 添加BOM结构弹窗组件 -->
    <quote-structure-dialog
        ref="structureDialogRef"
        @confirmQuoteProductUpdate="confirmQuoteProductUpdate"
    />
  </div>
</template>

<style scoped lang="scss">
.quote-form {
  padding: 20px;
  background: #fff;
  height: 100%;
  overflow-y: auto;

  .form-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;

    h3 {
      margin: 0;
      font-size: 18px;
    }
  }

  .form-actions {
    display: flex;
    justify-content: center;
    margin-top: 30px;
  }

  :deep(.el-input.is-disabled .el-input__wrapper) {
    background-color: var(--el-input-disabled-bg-color, var(--el-disabled-bg-color));
  }

  :deep(.el-input.is-disabled .el-input__inner) {
    color: var(--el-text-color-primary);
    -webkit-text-fill-color: var(--el-text-color-primary);
  }

  :deep(.el-textarea.is-disabled .el-textarea__inner) {
    color: var(--el-text-color-primary);
    -webkit-text-fill-color: var(--el-text-color-primary);
  }


  // 添加价格输入样式
  :deep(.el-input-group__append) {
    padding: 0 10px;
    background-color: var(--el-color-primary-light-8);
    color: var(--el-color-primary);
    font-weight: bold;
  }
}
</style>
